package com.ujcms.commons.web;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.springframework.lang.Nullable;

import java.io.Serial;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 响应信息主体
 *
 * @param <T>
 * @author liaoc
 */
@ToString
@NoArgsConstructor
@Accessors(chain = true)
@Data
public class HttpResult<T> implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;
    /**
     * 状态码：成功
     */
    public static final int SUCCESS = 0;
    /**
     * 状态码：失败
     */
    public static final int FAILURE = -1;

    @Schema(description = "逻辑状态码。0:成功, -1:失败。其它状态可以根据自己的实际逻辑随意使用")
    private Integer status = SUCCESS;

    /**
     * 数据
     */
    @Schema(description = "数据")
    private T data;

    /**
     * 信息
     */
    @Schema(description = "信息")
    @Nullable
    private String message;

    /**
     * 异常类的类名
     */
    @Schema(description = "异常类的类名")
    @Nullable
    private String exception;

    private String path;

    private String timestamp;


    public static <T> HttpResult<T> ok() {
        return restResult(null, SUCCESS, "success");
    }

    public static <T> HttpResult<T> ok(T data) {
        return restResult(data, SUCCESS, "success");
    }

    public static <T> HttpResult<T> ok(T data, String message) {
        return restResult(data, SUCCESS, message);
    }

    public static <T> HttpResult<T> failed() {
        return restResult(null, FAILURE, "fail");
    }

    public static <T> HttpResult<T> failed(String message) {
        return restResult(null, FAILURE, message);
    }

    public static <T> HttpResult<T> failed(T data) {
        return restResult(data, FAILURE, "fail");
    }

    public static <T> HttpResult<T> failed(T data, String message) {
        return restResult(data, FAILURE, message);
    }

    public static <T> HttpResult<T> failed(Integer status, T data, String message) {
        return restResult(data, status, message);
    }

    private static <T> HttpResult<T> restResult(T data, Integer status, String message) {
        HttpResult<T> apiResult = new HttpResult<>();
        apiResult.setStatus(status);
        apiResult.setData(data);
        apiResult.setMessage(message);
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        apiResult.setTimestamp(LocalDateTime.now().format(dtf));
        return apiResult;
    }
}